import constant from '../../constant';
import storage from '../../utils/storage';
import service from '../../service'

const state = {
    token: storage.getOrDefault(constant.STORAGE.USER.TOKEN, null),
    info: storage.getOrDefault(constant.STORAGE.USER.USER_INFO, {})
}

const actions = {
    userLogin({commit}, loginInfo) {
        return service.common.userLogin(loginInfo).then((r) => commit("SET_TOKEN", r));
    },
    userLogout({dispatch}) {
        return service.common.userLogout().then(() => dispatch("userRemove"))
    },
    userInfo({commit}) {
        return service.common.userInfo().then((r) => commit("SET_USERINFO", r) );
    },
    userRemove(commit) {
        commit("CLEAR_USER");
        commit("CLEAR_TOKEN");
        commit("RESET_PROCESS");
        commit("SET_MENU_GROUP", []);
        commit("SET_VIEW_ROUTES", []);
        commit("SET_MENU_LIST", 0);
        return Promise.resolve();
    }
}

const mutations = {
    SET_USERINFO(state, info) {
        state.info = info
        storage.set(constant.STORAGE.USER.USER_INFO, info)
    },
    SET_TOKEN(state, tokenInfo) {
        let token = tokenInfo.token
        let expire = tokenInfo.expire
        state.token = token
        storage.set(constant.STORAGE.USER.TOKEN, token, expire)
    },
    CLEAR_TOKEN(state) {
        state.token = null
        storage.remove(constant.STORAGE.USER.TOKEN)
    },
    CLEAR_USER(state) {
        state.info = {}
        storage.remove(constant.STORAGE.USER.USER_INFO)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
